package cn.edu.sdu.sol.intake_system.security;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.SecureRandom;

public class CustomBCryptPasswordEncoder implements PasswordEncoder {

    private final BCryptPasswordEncoder delegate;
    private final SecureRandom secureRandom;

    public CustomBCryptPasswordEncoder() {
        this.delegate = new BCryptPasswordEncoder();
        this.secureRandom = new SecureRandom();
    }

    @Override
    public String encode(CharSequence rawPassword) {
        // 生成随机盐值
        byte[] salt = new byte[16];
        secureRandom.nextBytes(salt);

        // 自定义加密逻辑，将盐值添加到密码中
        return delegate.encode(rawPassword + new String(salt));
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        // 自定义校验逻辑
        // 从编码后的密码中提取盐值
        byte[] salt = encodedPassword.substring(encodedPassword.length() - 16).getBytes();

        // 将用户输入的密码与提取的盐值相加后进行校验
        return delegate.matches(rawPassword + new String(salt), encodedPassword);
    }
}